package com.usian.common.exception;


import com.usian.model.common.dtos.ResponseResult;
import lombok.extern.log4j.Log4j2;
import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Log4j2
public class ExceptionCatch {

    // Key  value
    public static ImmutableMap<Class<? extends Throwable>,ResponseResult> EXCEPTIONS;
    public static ImmutableMap.Builder<Class<? extends Throwable>,ResponseResult> builder = EXCEPTIONS.builder();

    static {
        builder.put(IndexOutOfBoundsException.class,ResponseResult.errorResult(20006,"集合或数组超过了限制！"));
        builder.put(NullPointerException.class,ResponseResult.errorResult(20007,"对象不能为空！"));
        builder.put(ArithmeticException.class,ResponseResult.errorResult(20008,"除数不能为0！"));
    }
    // 所有的controller运行 它都能获取到

    // 抓取什么异常？  返回了 modelAndView
    @ExceptionHandler(value = {CustomException.class})
    @ResponseBody
    public ResponseResult CustomException(CustomException e){
        log.error("catch Exception:"+e.getMessage());
        // 处理异常
        return e.getResponseResult();
    }

    // 除了自定义异常以外  都是不可预知
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public ResponseResult CustomException(Exception e){
        log.error("ALL Exception:"+e.getMessage());
        e.printStackTrace();
        if(EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        // 根据异常类型 取值
        ResponseResult responseResult =  EXCEPTIONS.get(e.getClass());
        if(responseResult!=null){
            return responseResult;
        }
        // 处理异常   99999
        return ResponseResult.errorResult(99999,"出现不可预知异常！");
    }


    // 1. 先维护常用的异常类型
    // 2. 根据异常类型获取 值
    // 3. 如果有直接返回
    // 4. 如果没有 在返回99999

}
